package edu.zjut.hjg.saas.biz.service.impl;

import java.util.List;

import edu.zjut.hjg.saas.biz.dao.BabyDao;
import edu.zjut.hjg.saas.biz.dao.SchoolClassDao;
import edu.zjut.hjg.saas.biz.dao.UserLogDao;
import edu.zjut.hjg.saas.biz.model.SchoolClass;
import edu.zjut.hjg.saas.biz.model.UserLog;
import edu.zjut.hjg.saas.biz.service.SchoolClassService;
import edu.zjut.hjg.saas.biz.support.OperateType;

public class SchoolClassServiceImpl implements SchoolClassService {

    private UserLogDao     userLogDao;

    private SchoolClassDao schoolClassDao;

    private BabyDao        babyDao;

    public void setUserLogDao(UserLogDao userLogDao) {
        this.userLogDao = userLogDao;
    }

    public void setSchoolClassDao(SchoolClassDao schoolClassDao) {
        this.schoolClassDao = schoolClassDao;
    }

    public void setBabyDao(BabyDao babyDao) {
        this.babyDao = babyDao;
    }

    @Override
    public Integer create(SchoolClass schoolClass, String operator) {
        Integer id = schoolClassDao.create(schoolClass);
        UserLog userLog = new UserLog();
        userLog.setKindergarten(schoolClass.getKindergarten());
        userLog.setLoginId(operator);
        userLog.setOperateType(OperateType.INSERT);
        userLog.setDescription("创建了班级：" + schoolClass.getName());
        userLogDao.create(userLog);
        return id;
    }

    @Override
    public void deleteByIdAndAppId(int id, int appId, String operator) {
        SchoolClass schoolClass = schoolClassDao.findByIdAndAppId(id, appId);
        if (schoolClass == null) {
            throw new RuntimeException("no schoolClass found for id=" + id + " and appId=" + appId);
        }
        schoolClassDao.deleteByIdAndAppId(id, appId);
        babyDao.deleteBySchoolClassIdAndAppId(schoolClass.getId(), appId);
        UserLog userLog = new UserLog();
        userLog.getKindergarten().setId(appId);
        userLog.setLoginId(operator);
        userLog.setOperateType(OperateType.DELETE);
        userLog.setDescription("删除了一个班级:" + schoolClass.getName());
        userLogDao.create(userLog);
    }

    @Override
    public SchoolClass findByIdAndAppId(int id, int appId) {
        SchoolClass schoolClass = schoolClassDao.findByIdAndAppId(id, appId);
        if (schoolClass == null) {
            throw new RuntimeException("no schoolClass found for id=" + id + " and appId=" + appId);
        }
        return schoolClass;
    }

    @Override
    public List<SchoolClass> listByAppId(int appId) {
        return schoolClassDao.listByAppId(appId);
    }

    @Override
    public void update(SchoolClass schoolClass, int appId, String operator) {
        schoolClassDao.update(schoolClass);
        UserLog userLog = new UserLog();
        userLog.getKindergarten().setId(appId);
        userLog.setLoginId(operator);
        userLog.setOperateType(OperateType.UPDATE);
        userLog.setDescription("修改了班级:" + schoolClass.getName());
        userLogDao.create(userLog);
    }
}
